# coding=UTF-8
'''
Created on 2018年4月26日

@author: lijie
'''

import jsonpath

from utilites.http_helper import HttpHelper
from utilites.verification import Verification
from utilites.common import Common

class InterHelper():
    
    LOGIN = 'login'
    
    ACCOUNT_INFO = 'info'
    
    CHECKMOBILE = 'checkmobile'

    def __init__(self):
        self.comm = Common()

    def send_post_request(self, module, inter_name, param={},is_url_param=False):
        '''arg: module  模块名，
                inter_name 接口名， 
                param  请求参数 默认为空字典  
                is_url_param   是否通过url传参
        '''
        res = HttpHelper().post(module, inter_name,param,is_url_param)
        return res
    
    def send_get_request(self, module, inter_name, param={}):
        '''arg: module  模块名，
                inter_name 接口名， 
                param  请求参数 默认为空字典  
                is_url_param   是否通过url传参
        '''
        res = HttpHelper().get(module, inter_name,param)
        return res

    def get_target_item_from_response(self, res_str, exp):
        '''通过jsonpath在返回json中取得需要的目标项
        '''
        _target = jsonpath.jsonpath(res_str, exp)
        if _target != False:
            self.comm.logger_info("get the items: " + str(_target))
            return _target[0]
        else:
            return None

    def get_verify_str(self, exp_node, **exp_kvs):
        '''exp_node    期待的节点值
           **exp_kvs   期待的该节点包含的属性及属性值，如 parentId=1,name=aa,不定长度参数，可以写多个k=v以逗号隔开
        '''
        i = 0  # 计数器，当做最后一项拼接时不加and
        kv_str = ''
        for k, v in exp_kvs.items():
            if i < len(exp_kvs) - 1:
                kv_str += "@." + k + "==" + str(v) + " and "
                i += 1
            else:
                kv_str += "@." + k + "==" + str(v)
        #                 kv_str+="@."+k+"=="+"'"+v+"' "
        jsonpath_str = "$.." + exp_node + "[?(" + kv_str + ")]"
        return jsonpath_str

    def verify_response(self, res_json, exp_node, **exp_kvs):
        '''res_json   返回json
           exp_node    期待的节点值
           **exp_kvs   期待的该节点包含的属性及属性值，如 parentId=1,name=aa,不定长度参数，可以写多个k=v以逗号隔开
        '''
        item = []
        jpath = self.get_verify_str(exp_node, **exp_kvs)
        target = self.get_target_item_from_response(res_json, jpath)
        if target != None:
            item.append(target)
        Verification().check_size_more_zero(item, "期待的返回项没有找到！！--expected: " + jpath)
        return item[0]
    
    def check_response(self,res_json,**exp_kvs):
        for k, v in exp_kvs.items():
            actual=jsonpath.jsonpath(res_json,"$.." + k)[0]
            if str(actual)!=v:
                Common().logger_error("expect value of ["+k+"] failed!! expected:"+v+" but response "+str(actual))
            else:
                Common().logger_info("expect value of ["+k+"] passed!!!,get value:"+str(actual))
